<?php

namespace app\admin\model\weixin;

use think\Model;
use fast\Random;
use think\Db;
use think\Exception;
use addons\weixin\library\WechatService;

class User extends Model
{
    // 表名
    protected $name = 'weixin_user';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'subscribe_time_text'
    ];

    public function getSubscribeTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['subscribe_time']) ? $data['subscribe_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setSubscribeTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public function fauser()
    {
        return $this->belongsTo('app\admin\model\User', 'uid', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 微信授权成功后
     * @param $event
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function onWechatOauthAfter($wechatInfo, $spreadId, $login_type)
    {
        if (isset($wechatInfo['unionid'])) {
            $where['unionid'] = $wechatInfo['unionid'];
        } else {
            $where['openid'] = $wechatInfo['openid'];
        }
        $uid = self::where($where)->value('uid');
        if ($uid) {
            //更新微信会员
            self::updateWechatUser($wechatInfo, $uid, 'uid');
            //检查是否存在主会员数据
            if (\app\admin\model\User::get($uid)) {
                self::updateUser($wechatInfo, $uid);
            }
        } else {
            if (isset($wechatInfo['subscribe_scene'])) {
                unset($wechatInfo['subscribe_scene']);
            }
            if (isset($wechatInfo['qr_scene'])) {
                unset($wechatInfo['qr_scene']);
            }
            if (isset($wechatInfo['qr_scene_str'])) {
                unset($wechatInfo['qr_scene_str']);
            }
            $userModel = self::addUser($wechatInfo);
            //设置推荐人
            $wechatInfo['parent_id'] = $spreadId;
            //设置会员主表ID
            $wechatInfo['uid'] = $uid = $userModel->id;
            //新增微信会员
            self::addWechatUser($wechatInfo);
        }
        return $uid;
    }

    /**
     * uid获取小程序Openid
     * @param string $uid
     * @return bool|mixed
     */
    public static function getOpenId($uid = '')
    {
        if ($uid == '') {
            return false;
        }
        return self::where('uid', $uid)->value('routine_openid');
    }

    /**
     * TODO 用uid获得openid
     * @param $uid
     * @param string $openidType
     * @return mixed
     * @throws \Exception
     */
    public static function uidToOpenid($uid, $openidType = 'routine_openid')
    {
        $openid = self::where('uid', $uid)->value($openidType);
        return $openid;
    }

    /**
     * TODO 用openid获得uid
     * @param $openid
     * @param string $openidType
     * @return mixed
     */
    public static function openidTouid($openid, $openidType = 'openid')
    {
        return self::where($openidType, $openid)->where('user_type', '<>', 'h5')->value('uid');
    }

    /**
     * 添加一条数据
     * @param $data
     * @param $id
     * @param $field
     * @return bool $type 返回成功失败
     */
    public static function addWechatUser($data)
    {
        $model = new self;
        return $model->allowField(true)->save($data);
    }

    /**
     * 修改一条数据
     * @param $data
     * @param $id
     * @param $field
     * @return bool $type 返回成功失败
     */
    public static function updateWechatUser($data, $id, $field = null)
    {
        $model = new self;
        return $model->allowField(true)->save($data, [$field => $id]);
    }

    /**
     * 新建微信会员
     * @param $data
     * @param $id
     * @param $field
     * @return bool $type 返回成功失败
     */
    public static function addUser($wechatUser)
    {
        $user = false;
        //账号注册时需要开启事务,避免出现垃圾数据
        Db::startTrans();
        try {
            $salt = Random::alnum();
            $data = [
                'username'  => 'wx' . time(),
                'salt'      => $salt,
                'password'  => md5(md5(time()) . $salt),
                'nickname'  => $wechatUser['nickname'] ?: '',
                'avatar'    => $wechatUser['headimgurl'] ?: '',
                'jointime'  => time(),
                'joinip'    => request()->ip(),
                'logintime' => time(),
                'loginip'   => request()->ip(),
                'status'    => 'normal',
                'group_id'  => '1',
            ];
            $user = \app\admin\model\User::create($data, true);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
        }
        return $user;
    }

    /**
     * 更新用户信息
     * @param $wechatUser 用户信息
     * @param $uid 用户uid
     * @return bool|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function updateUser($wechatUser, $uid)
    {
        $userInfo = \app\admin\model\User::where('id', $uid)->find();
        if (!$userInfo) {
            return;
        }
        $data = [
            'nickname' => $wechatUser['nickname'] ?: '',
            'avatar' => $wechatUser['headimgurl'] ?: '',
            'logintime' => time(),
            'loginip' => request()->ip()
        ];
        $model = new \app\admin\model\User();
        return $model->save($data, ['id' => $uid]);
    }


    /**
     * 得到微信标签
     * @author Created by Xing <464401240@qq.com>
     */
    public static function getTag()
    {
        $list = Db::name('weixin_cache')->where('key', 'wechat_tag')->value('result');
        if (empty($list)) {
            try {
                $tag = WechatService::userTagService()->lists()->toArray()['tags'] ?: array();
            } catch (\Exception $e) {
                return array();
            }
            $list = [];
            foreach ($tag as $g) {
                $list[$g['id']] = $g;
            }
            $list = json_encode($list, JSON_UNESCAPED_UNICODE);
            Db::name('weixin_cache')->insert([
                'result' => $list, 'add_time' => time(), 'key' => 'wechat_tag'
            ]);
        }
        $list = json_decode($list, true);
        return $list;
    }


    /**
     * 得到微信分组
     * @author Created by Xing <464401240@qq.com>
     */
    public static function getGroup()
    {
        $list = Db::name('weixin_cache')->where('key', 'wechat_group')->value('result');
        if (empty($list)) {
            try {
                $group = WechatService::userGroupService()->lists()->toArray()['groups'] ?: array();
            } catch (\Exception $e) {
                return array();
            }
            $list = [];
            foreach ($group as $g) {
                $list[$g['id']] = $g;
            }
            $list = json_encode($list, JSON_UNESCAPED_UNICODE);
            Db::name('weixin_cache')->insert([
                'result' => $list, 'add_time' => time(), 'key' => 'wechat_group'
            ]);
        }
        $list = json_decode($list, true);
        return $list;
    }
}
